package com.map;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends MapActivity {

	MapView map = null;
	LocationManager locaMana;
	MyLocationOverlay mylocation;
	GeoPoint bachkhoa, mypoint;
	Location location;
	private int intDistance;
	private float distance;
	AlertDialog.Builder direction;
	ImageButton buttonText;
	ImageButton buttonAudio;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		
		map = (MapView) findViewById(R.id.map);
		map.getController().setZoom(15);
		map.setBuiltInZoomControls(true); 
 
		buttonText = (ImageButton)findViewById(R.id.bt_text);
		buttonAudio = (ImageButton)findViewById(R.id.bt_audio);
		
		bachkhoa = new GeoPoint((int) (21.006357 * 1000000.0),
				(int) (105.8429911 * 1000000.0));

		// lay toa do vi tri hien tai
		locaMana = (LocationManager) getSystemService(LOCATION_SERVICE);
		location = locaMana.getLastKnownLocation(locaMana.getBestProvider(
				new Criteria(), true));
		mypoint = new GeoPoint((int) (location.getLatitude() * 1000000.0),
				(int) (location.getLongitude() * 1000000.0));

		// hien thi vi tri hien tai tren ban do
		map.getController().animateTo(mypoint);
		mylocation = new MyLocationOverlay(this, map);
		mylocation.enableMyLocation();
		map.getOverlays().add(mylocation);
		map.postInvalidate();

		// hien thi mot vi tri tren ban do
		List mapOverlays = map.getOverlays();
		Drawable drawable = this.getResources()
				.getDrawable(R.drawable.icon_map);
		MyItemzedOverlay myItem = new MyItemzedOverlay(drawable, this, true);
		OverlayItem overlay = new OverlayItem(bachkhoa, "Xin Chào!",
				"Trường Đại Học Bách Khoa Hà Nội");
		myItem.addOverlay(overlay);
		mapOverlays.add(myItem);

		// canh bao khi gan truong bach khoa
		Location bk = new Location("bach khoa");
		bk.setLatitude(21.006357);
		bk.setLongitude(105.8429911);
		distance = location.distanceTo(bk);
		intDistance = Math.round(distance);

		if (intDistance < 200) {
			View reportView = getLayoutInflater()
					.inflate(R.layout.report, null);
			AlertDialog.Builder report = new AlertDialog.Builder(this);
			report.setTitle("Thông Báo");
			report.setView(reportView);
			report.setNegativeButton("OK", null);
			report.show();
		}

		buttonText.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent in = new Intent(MainActivity.this, GetDirectionbyText.class);
				String myLan = String.valueOf(location.getLatitude());
				String myLong = String.valueOf(location.getLongitude());
				in.putExtra("MYLAN", myLan);
				in.putExtra("MYLONG", myLong);
				startActivity(in);
			}
		});
		
		buttonAudio.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent in = new Intent(MainActivity.this, GetDirectionbyAudio.class);
				String myLan = String.valueOf(location.getLatitude());
				String myLong = String.valueOf(location.getLongitude());
				in.putExtra("MYLAN", myLan);
				in.putExtra("MYLONG", myLong);
				startActivity(in);
			}
		});
	}

	LocationListener onLocationChange = new LocationListener() {
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplication(), "GPS off", 1).show();

		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			String loca = "You are at ( " + location.getLatitude() + ";"
					+ location.getLongitude() + " )";
			Toast.makeText(getApplicationContext(), loca, Toast.LENGTH_LONG)
					.show();
			locaMana.removeUpdates(onLocationChange);

		}
	};
	// tim va danh dau dia diem tren ban do
	private void showLocation() {

		final View directionView = getLayoutInflater().inflate(
				R.layout.direction, null);
		direction = new AlertDialog.Builder(MainActivity.this);
		direction.setTitle("Nhập địa điểm");
		direction.setView(directionView);
		direction.setIcon(R.drawable.bytext);

		direction.setPositiveButton("Tìm",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						EditText edstart_point = (EditText) directionView
								.findViewById(R.id.start_point);
						EditText edend_point = (EditText) directionView
								.findViewById(R.id.end_point);
						String str_start_point = edstart_point.getText()
								.toString();
						String str_end_point = edend_point.getText().toString();
						GeoPoint end_point = convertName(str_end_point);
						if (str_start_point.equalsIgnoreCase("từ đây")) {
							show(end_point, str_end_point);
							show(mypoint, "Vị trí của bạn");
						} else {
							GeoPoint start_point = convertName(str_start_point);
							show(start_point, str_start_point);
							show(end_point, str_end_point);
						}

					}

				});

		direction.setNegativeButton("Thoát", null);
		direction.show();
	}

	
	// ve diem tren ban do
	private void show(GeoPoint geopoint, String str) {
		List mapOverlays = map.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.icon2);
		MyItemzedOverlay myItem = new MyItemzedOverlay(drawable, this, false);
		OverlayItem overlay = new OverlayItem(geopoint, "Xin Chào!", str);
		myItem.addOverlay(overlay);
		mapOverlays.add(myItem);

	}

	// chuyen doi ten sang geopoint
	private GeoPoint convertName(String str_point) {
		GeoPoint point = null;
		Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
		try {
			List<Address> addresses = geoCoder
					.getFromLocationName(str_point, 5);
			if (addresses.size() > 0) {
				point = new GeoPoint(
						(int) (addresses.get(0).getLatitude() * 1000000.0),
						(int) (addresses.get(0).getLongitude() * 1000000.0));
			} else {
				Toast.makeText(
						getApplicationContext(),
						"Địa điểm bạn nhập không chính xác!\n"
								+ "Vui lòng nhập lại.", Toast.LENGTH_LONG)
						.show();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return point;

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == R.id.menu_location) {
			// locaMana.requestLocationUpdates(LocationManager.GPS_PROVIDER,
			// 1000, 1, onLocationChange);
			map.getController().animateTo(mypoint);
			String loca = "Bạn đang ở tọa độ ( " + location.getLatitude() + ","
					+ location.getLongitude() + " )";
			Toast.makeText(getApplicationContext(), loca, Toast.LENGTH_LONG).show();

			return true;
			
		}else if (item.getItemId() == R.id.menu_findlocation) {
			showLocation();
		}

		return super.onOptionsItemSelected(item);
	}


	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}
